package com.cqhz.quwan.ui.buy.adapter

import android.content.Context
import android.widget.CheckBox
import android.widget.Toast
import com.cqhz.quwan.R
import com.cqhz.quwan.ui.base.AbsAdapter
import com.cqhz.quwan.util.slice

class BallAdapter(context: Context, layoutResId: Int) : AbsAdapter<Int>(context, layoutResId) {
    private val checks = ArrayList<Int>()
    var numberFormat = true
    var selectMax = -1
    var selectMin = -1
    var listener: ((List<Int>) -> Unit)? = null
    override fun handlerViewHolder(viewHolder: ViewHolder,position: Int, itemData: Int?) {
        viewHolder.setText(R.id.item_ball_cb,if (numberFormat) itemData?.slice(2) else itemData?.toString())
        if(checks.contains(itemData)){
            viewHolder.checked(R.id.item_ball_cb,true)
        }else {
            viewHolder.checked(R.id.item_ball_cb,false)
        }
        val cb = viewHolder.find<CheckBox>(R.id.item_ball_cb)
        cb.tag = itemData
        cb.setOnCheckedChangeListener{v,checked ->
            val i = v.tag as Int
            if(checks.contains(i)&&!checked){
                checks.remove(i)
                listener?.invoke(checks)
            }else if(!checks.contains(i)&&checked){
                if(selectMax != -1&&checks.size >= selectMax){
                    Toast.makeText(context,"最大可选${selectMax}个",Toast.LENGTH_SHORT).show()
                    v.isChecked = false
                    return@setOnCheckedChangeListener
                }
                checks.add(i)
                listener?.invoke(checks)
            }
        }
    }
    fun addChecks(checks:List<Int>){
        this.checks.addAll(checks)
        listener?.invoke(checks)
        notifyDataSetChanged()
    }
    fun setChecks(checks:List<Int>?){
        setChecks(checks,true)
    }
    fun setChecks(checks:List<Int>?,invoke:Boolean){
        if(checks != null){
            this.checks.clear()
            this.checks.addAll(checks)
            if(invoke){
                listener?.invoke(checks)
            }
            notifyDataSetChanged()
        }
    }
    fun clearChecks(){
        this.checks.clear()
        listener?.invoke(checks)
        notifyDataSetChanged()
    }
}